<?php

namespace App\Providers;

use App\Commons\Libs\JWTAuth\CustomEloquentUserProvider;
use Auth;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Gate;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        // 'App\Models\Model' => 'App\Policies\ModelPolicy',
    ];

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();

        //
    }

    public function register()
    {
        // 自定义用户提供者，默认每次通过token查询用户是否存在，自定义提供者可在查询中增加缓存，减少数据库查询，但是用户状态更新不及时
        // 需要手动调用CustomEloquentUserProvider::refresh($key)清除登录缓存
        Auth::provider(
            'cache_eloquent',
            function ($app, array $config) {
                // 返回 Illuminate\Contracts\Auth\UserProvider 实例...
                $model = $config['model'];
                $fields = $config['fields'];
                $auth_model = $config['auth_model'];

                return $app->make(CustomEloquentUserProvider::class, compact('model', 'auth_model', 'fields'));
            }
        );
    }
}
